package pinboard.dataLayer.potocol.op;

import com.google.gson.Gson;

import pinboard.dataLayer.potocol.instructFormat.response.ChangePasswordResult;
import pinboard.dataLayer.potocol.instructFormat.response.EditProfileResult;
import pinboard.dataLayer.potocol.instructFormat.response.ExitMeetingResult;
import pinboard.dataLayer.potocol.instructFormat.response.JoinMeetingResult;
import pinboard.dataLayer.potocol.instructFormat.response.UpdateMeetingStateResult;
import pinboard.dataLayer.potocol.instructFormat.Response;

class ResponseDecoder {

    private ResponseDecoder() {

    }

    static ResponseDecoder decoder = new ResponseDecoder();

    public static void filter(Response input, InstructClientDecodeListener listener) {
        decoder.filterIns(input, listener);
    }

    //region 封装辅助类
    private class Bag {
        public boolean allow = false;
        public Object result = null;
    }

    private class BagCreator {
        Gson gson = new Gson();
        Response response;

        public BagCreator(Response input) {
            response = input;
        }

        public <T> Bag create(String method, Class<T> tClass) {
            Bag bag = new Bag();
            bag.allow = false;
            if (response.method.equalsIgnoreCase(method)) {
                bag.result = gson.fromJson(response.result, tClass);
                bag.allow = true;
            }
            return bag;
        }
    }
    //endregion

    private void filterIns(Response input, InstructClientDecodeListener listener) {
        BagCreator creator = new BagCreator(input);
        Bag bag;
        if ((bag = creator.create("Login2", JoinMeetingResult.class)).allow) {
            listener.onJoinMeeting(input, (JoinMeetingResult) bag.result);
        } else if ((bag = creator.create("KeepAlive", String.class)).allow) {
            listener.onKeepAlive(input);
        } else if ((bag = creator.create("JoinMeeting", JoinMeetingResult.class)).allow) {
            listener.onJoinMeeting(input, (JoinMeetingResult) bag.result);
        } else if ((bag = creator.create("ExitMeeting", ExitMeetingResult.class)).allow) {//TODO
            listener.onExitMeeting(input, (ExitMeetingResult) bag.result);
        } else if ((bag = creator.create("ChangePassword", ChangePasswordResult.class)).allow) {//TODO
            listener.onChangePassword(input, (ChangePasswordResult) bag.result);
        } else if ((bag = creator.create("EditProfile", EditProfileResult.class)).allow) {//TODO
            listener.onEditProfile(input, (EditProfileResult) bag.result);
        } else if ((bag = creator.create("UpdateMeetingState", UpdateMeetingStateResult.class)).allow) {//TODO
            listener.onUpdateMeetingState(input, (UpdateMeetingStateResult) bag.result);
        } else {
            //TODO LogoutResult
            //TODO log here
        }
    }
}
